package com.heyi.nettylong.server.handler;

import com.heyi.nettylong.common.MessageHandler;
import com.heyi.nettylong.common.protobuf.Command;
import com.heyi.nettylong.common.protobuf.Message;
import com.heyi.nettylong.common.protobuf.Command.CommandType;
import com.heyi.nettylong.common.util.MessageUtil;
import com.heyi.nettylong.common.util.SpringBeanFactory;
import com.heyi.nettylong.common.MessageRepository;
import com.heyi.nettylong.server.listener.ChannelDataListener;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


/** 其他业务拓展模板参考
  * @Author: myzf
  * @Date: 2019/2/23 13:24
  * @param
*/
@ChannelHandler.Sharable
public class ServerDataHandler extends ChannelInboundHandlerAdapter{
	public Logger log = LoggerFactory.getLogger(this.getClass());

	private final ChannelDataListener channelDataListener = SpringBeanFactory.getBean(ChannelDataListener.class);
	private final AttributeKey<String> clientInfo = AttributeKey.valueOf("clientInfo");

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		Message.MessageBase msgBase = (Message.MessageBase)msg;
		log.debug("接收到[{}]数据 cmd:{},data:{}", msgBase.getClientId(), msgBase.getCmd(), msgBase.getData());
		// 验证token
		String token = ctx.attr(clientInfo).get().split(",")[1];
		if(StringUtils.isEmpty(token) || !token.equals(msgBase.getToken())){
			log.info("客户端[{}]token错误，拒绝连接", msgBase.getClientId());
			ctx.writeAndFlush(MessageUtil.build(msgBase.getClientId(), Command.CommandType.AUTH_BACK, "权限验证没通过")).addListener((ChannelFuture futureListener)->{
				ctx.channel().close();
			});
			return;
		}
		if(msgBase.getCmd().equals(CommandType.PUSH_DATA)){
			if(channelDataListener != null) {
				MessageHandler messageHandler = new MessageHandler(ctx, msgBase);
				try {
					channelDataListener.receiveData(messageHandler);
				} catch (Exception e) {
					log.error("channelDataListener发生错误：" + e);
				}
			}
		}else if(msgBase.getCmd().equals(CommandType.PUSH_DATA_BACK)){
			MessageRepository.put(msgBase);
		}else {
			log.error("收到未知消息【"+msgBase.getClientId()+","+msgBase.getCmd()+"】："+ msgBase.getData());
		}

		ReferenceCountUtil.release(msg);
	}

}
